﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EmoneyWeiXinCommon;
using EmoneyWeiXinBLL;
using EmoneyWeiXinEntity;
using System.IO;
using System.Data;
using System.Drawing;
using EmoneyWeiXin.Filter;
using System.Net;
namespace EmoneyWeiXin.Controllers
{
    public class TwoCodeController : Controller
    {
        //
        // GET: /TwoCode/
        [LoginAuthorizeAttribute]
        public ActionResult Index()
        {
            return View();
        }
        [LoginAuthorizeAttribute]
        //二维码参数管理页面
        public ActionResult TwoCodeTypeManager(int weixinid = 0)
        {
            ViewBag.leftid = int.Parse(Request["leftid"]);
            ViewBag.weixinid = weixinid;
            return View();
        }

        //二维码参数管理页面:添加修改删除
        public string UpdateTwoCodeType()
        {
            var uid = 0;
            UserEntity us = LoginUserInfo.GetLoginUserCache();
            if (us != null)
                uid = us.id;
            int weixinid = int.Parse(Request["weixinid"]);
            int iRe = 0;
            var flag = Request["op"].Trim();//flag=-1表示删除
            var ID = int.Parse(Request["id"].Trim());//ID=0表示新增，否则表示修改
            if (flag != "-1")
            {
                var name = Request["name"].Trim();
                var beginval = int.Parse(Request["beginval"].Trim());
                var endval = int.Parse(Request["endval"].Trim());
                var memo = Request["memo"].Trim(); ;

                //var data = (IList<TwoCode_TypeModel>)ViewState["data"];
                List<TwoCode_TypeModel> data = new List<TwoCode_TypeModel>();
                data = TwoCodeManager.getTwoCodeType(weixinid);
                //if (TwoCodeManager.HasOtherRank(ID, beginval, data))
                //{
                //    return "区间开始值已经存在其他区间！";
                //}
                //if (TwoCodeManager.HasOtherRank(ID, endval, data))
                //{
                //    return "区间结束值已经存在其他区间！";
                //}
                var ir = TwoCodeManager.HasOtherRank2(ID, beginval, endval, data);
                if (ir == 1)
                {
                    return "区间开始值已经存在其他区间！";
                }
                else if (ir == 2)
                {
                    return "区间结束值已经存在其他区间！";
                }
                else if (ir == 3)
                {
                    return "区间开始值与区间结束值已经包含了其他区间！";
                }
                TwoCode_TypeModel type = new TwoCode_TypeModel();
                if (ID > 0)
                {
                    type.Sign = 1;
                }
                else
                {
                    type.Sign = 0;
                }
                type.ID = ID;
                type.name = name;
                type.begin_val = beginval;
                type.end_val = endval;
                type.memo = memo;
                type.creator = uid;
                //type.creator = 1;
                type.updatetime = DateTime.Now;
                type.weixinid = weixinid;
                iRe = TwoCodeManager.UpdateTwoCodeType(type);
            }
            else
            {
                iRe = TwoCodeManager.deleteTwoCodeType(ID, weixinid);

            } if (iRe > 0)
            {
                return "1";
            }
            else
            {
                return "-1";
            }
        }
        //二维码参数管理页面-查询操作
        public string QueryTwoCodeType()
        {
            //int weixinid = 1;
            var weixinid = int.Parse(Request["weixinid"]);
            var pindex = int.Parse(Request["pindex"]);
            var psize = int.Parse(Request["psize"]);
            int total = 0;
            var jsonString = "";
            IList<TwoCode_TypeModel> data = TwoCodeManager.getTwoCodeType(weixinid, pindex, psize, out total);
            if (data != null && data.Count > 0)
            {
                jsonString = JsonTools.ToJson(data);
            }
            return total.ToString() + "~" + jsonString;
        }
        [LoginAuthorizeAttribute]
        //二维码参数生成页面
        public ActionResult TwoCodeInfoManager(int weixinid = 0)
        {
            ViewBag.leftid = int.Parse(Request["leftid"]);
            ViewBag.weixinid = weixinid;
            //var data = TwoCodeManager.getTwoCodeType(weixinid);
            //ViewBag.typeinfo = data;
            return View();
        }
        public string GetTwoCodeType()
        {
            var weixinid = int.Parse(Request["weixinid"]);
            var data = TwoCodeManager.getTwoCodeType(weixinid);
            return JsonTools.ToJson(data);
        }

        //二维码参数生成页面:保存操作
        public string UpdateTwoCodeInfo()
        {
            var uid = 0;
            UserEntity us = LoginUserInfo.GetLoginUserCache();
            if (us != null)
                uid = us.id;
            int iRe = 0;
            var flag = Request["flag"].Trim();//flag=-1表示删除
            var ID = int.Parse(Request["id"]);//ID=0表示新增，否则表示修改
            if (flag != "-1")
            {
                var weixinid = int.Parse(Request["weixinid"]);
                var typeid = int.Parse(Request["typeid"]); ;
                var name = Request["name"];
                var value = int.Parse(Request["value"]);
                var status = int.Parse(Request["status"]);
                var memo = Request["memo"].Trim();
                var imgurl = Request["imgurl"].Trim();
                var kf_id = Request["kfid"].Trim();
                //List<TwoCode_InfoModel> data = new List<TwoCode_InfoModel>();
                //var bl = TwoCodeManager.HasReVal(ID, value, data);
                //if (bl)
                //{
                //    return "参数值不能重复，请重新输入！";
                //}
                TwoCode_InfoModel info = new TwoCode_InfoModel();
                if (ID > 0)
                {
                    info.Sign = 1;
                }
                else
                {
                    info.Sign = 0;
                }
                info.ID = ID;
                info.typeid = typeid;
                info.name = name;
                info.value = value;
                info.status = status;
                info.memo = memo;
                info.creator = uid;
                info.updatetime = DateTime.Now;
                info.imgurl = imgurl;
                info.kf_id = kf_id;
                info.weixinid = weixinid;
                iRe = TwoCodeManager.UpdateTwoCodeInfo(info);
            }
            else
            {
                iRe = TwoCodeManager.deleteTwoCodeInfo(ID, 3);
            }
            if (iRe > 0)
            {
                return "1";
            }
            else
            {
                return "-1";
            }
        }

        //二维码参数生成页面-查询操作
        public string getTwoCodeList()
        {
            var data = "";
            //checkSession();
            int size = int.Parse(Request["size"]);
            if (size == 0 || size > 50) size = 10;
            int index = int.Parse(Request["index"]);

            TwoCode_InfoModel obj = new TwoCode_InfoModel();
            obj.typeid = int.Parse(Request["typeid"]);
            obj.name = Request["name"].Trim();
            if (Request["value"].Trim() == "")
            {
                obj.value = -1;
            }
            else
            {
                try
                {
                    obj.value = int.Parse(Request["value"].Trim().Trim());
                }
                catch
                {
                    data = "参数值格式不正确";
                }
            }
            obj.status = int.Parse(Request["status"]);
            obj.memo = Request["memo"].Trim();
            obj.weixinid = int.Parse(Request["weixinid"]); ;
            int total = 0;
            IList<TwoCode_InfoModel> list = TwoCodeManager.getTwoCodeInfo(size, index, obj, out total);
            if (list != null && list.Count > 0)
            {
                data = JsonTools.ToJson(list);
            }
            return total.ToString() + "~" + data;
        }

        //二维码参数生成页面-生成预览操作
        public string CreateTwoCode()
        {
            //var id = int.Parse((Request["id"] == null || Request["id"] == "") ? "0" : Request["id"]);
            //var weixinid = int.Parse(Request["weixinid"]);
            //var data = TwoCodeManager.getTwoCodeInfo(weixinid);
            //var value = int.Parse(Request["value"]);
            //var bl = TwoCodeManager.HasReVal(id, value, data);
            //if (bl)
            //{
            //    return "-1," + "参数值不能重复，请重新输入！";
            //}
            //var ret = TwoCodeManager.GetTwoCodeMap(weixinid, value);
            //if (ret != "")
            //{
            //    return "1," + TwoCodeManager.GetTwoCodeMap(weixinid, value);
            //}
            //else
            //{
            //    return "-1," + "生成失败！";
            //}
            var id = int.Parse((Request["id"] == null || Request["id"] == "") ? "0" : Request["id"]);
            var weixinid = int.Parse(Request["weixinid"]);
            var data = TwoCodeManager.getTwoCodeInfo(weixinid);
            var value = int.Parse(Request["value"]);
            var bl = TwoCodeManager.HasReVal(id, value, data);
            if (bl)
            {
                return "-1," + "参数值不能重复，请重新输入！";
            }
            var ticket = TwoCodeManager.CreateTwoCodeTicket(weixinid, value);
            if (ticket != "")
            {
                weixinUserBLL bll = new weixinUserBLL();
                //string weixinname = Server.UrlEncode(bll.getWeixinUserByID(weixinid).title);
                //string remark = Server.UrlEncode(bll.getWeixinUserByID(weixinid).remark);
                //string weixinNumber = Server.UrlEncode(bll.getWeixinUserByID(weixinid).weixinNumber);
                var weixinEntity = bll.getWeixinUserByID(weixinid);
                string weixinname = weixinEntity.title;
                string remark = weixinEntity.remark;
                string weixinNumber = weixinEntity.weixinNumber;
                // var selPicUrldt = Config.selPicUrldt + "TwoCode/UserEwm?tiket=" + ticket + "&weixinname=" + weixinname + "&remark=" + remark + "&weixinNumber=" + weixinNumber;
                // Bitmap m_Bitmap = WebSiteThumbnail.GetWebSiteThumbnail(selPicUrldt, 180, 240, 180, 240);
                Bitmap m_Bitmap = GetTcodeBitMap(ticket, weixinname, remark, weixinNumber);
                if (m_Bitmap != null)
                {
                    // StringCommon.CreateFile(Config.FileStaticUrl + "/" + weixinid + "/");
                    //var url = Config.FileStaticUrl + "/" + weixinid + "/" + weixinid.ToString() + "_" + value.ToString() + ".jpg";
                    //m_Bitmap.Save(url);
                    string imgName = weixinid + "_" + value.ToString() + ".jpg";
                    MemoryStream ms = new MemoryStream();
                    m_Bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    byte[] imgdata = ms.GetBuffer();
                    HttpUploadFile fileUp = new HttpUploadFile();
                    string result = fileUp.UploadFile(Config.fileuploadUrl, "EmoneyWeiXin", imgName, imgdata);//b：byte[]类型（上传文件的文件流）
                    var obj = JsonTools.ToObject<uploadEntity>(result);
                    var state = obj.state;
                    return "1," + obj.url;
                }
                else
                {
                    return "-1," + "生成失败！";
                }
            }
            else
            {
                return "-1," + "生成失败！";
            }

        }
        [LoginAuthorizeAttribute]
        //二维码统计-页面
        public ActionResult TwoCodeStat(int weixinid = 0)
        {
            ViewBag.leftid = int.Parse(Request["leftid"]);
            ViewBag.weixinid = weixinid;
            var data = TwoCodeManager.getTwoCodeType(weixinid);
            ViewBag.typeinfo = data;
            return View();
        }
        public string GetTwoCodeStatList()
        {
            //checkSession();
            var data = "";
            var ret = "";
            int total = 0;
            int weixinid = int.Parse(Request["weixinid"]);
            int size = int.Parse(Request["size"]);
            int index = int.Parse(Request["index"]);
            var type = int.Parse((Request["type"] == "" || Request["type"] == null) ? "0" : Request["type"]);
            var value = int.Parse((Request["value"] == "" || Request["value"] == null) ? "0" : Request["value"]);
            var list = TwoCodeManager.getWeixinAttentionLogStat(weixinid, type, value, index, size, out total);
            if (list != null && list.Tables.Count > 0)
            {
                data = JsonTools.ToJson(list.Tables[0]);
            }
            ret = total.ToString() + "~" + data;
            return ret;
        }
        [LoginAuthorizeAttribute]
        //二维码统计详情页面
        public ActionResult TwoCodeStatDetail()
        {
            ViewBag.leftid = int.Parse(Request["leftid"]);
            ViewBag.weixinid = Server.UrlDecode(Request["weixinid"]);
            ViewBag.value = Server.UrlDecode(Request["value"]);
            ViewBag.name = Server.UrlDecode(Request["name"]);
            ViewBag.date = Server.UrlDecode(Request["date"]);
            return View();
        }
        public string GetTwoCodeStatDetail()
        {
            var data = "";
            var ret = "";
            int total = 0;
            int weixinid = int.Parse(Request["weixinid"]);
            int size = int.Parse(Request["size"]);
            int index = int.Parse(Request["index"]);
            var tcode = int.Parse(Request["value"]);
            var list = TwoCodeManager.getWeixinuser_getByTcode(weixinid, tcode, index, size, out total);
            if (list != null && list.Tables.Count > 0)
            {
                data = JsonTools.ToJson(list.Tables[0]);
            }
            ret = total.ToString() + "~" + data;
            return ret;
        }
        //生产带文字的二维码
        //public ActionResult UserEwm()
        //{
        //    var tiket = Request["tiket"];
        //    var weixinname = Server.UrlDecode(Request["weixinname"]);
        //    var remark = Server.UrlDecode(Request["remark"]);
        //    var weixinNumber = Server.UrlDecode(Request["weixinNumber"]);
        //    if (string.IsNullOrEmpty(tiket))
        //    {
        //        tiket = "";
        //    }
        //    ViewBag.ImageUrl = Config.WeiXin_MpUrl + "showqrcode?ticket=" + HttpUtility.UrlEncode(tiket);
        //    ViewBag.weixinname = weixinname;
        //    ViewBag.remark = remark;
        //    ViewBag.weixinNumber = weixinNumber;
        //    return View();
        //}


        public Bitmap GetTcodeBitMap(string tiket, string weixinName, string remark, string weixinNumber)
        {
            try
            {
                string imgUrl = Config.WeiXin_MpUrl + "showqrcode?ticket=" + HttpUtility.UrlEncode(tiket);
                WebClient mywebclient = new WebClient();
                byte[] bytes = mywebclient.DownloadData(imgUrl);
                Image img = Image.FromStream(new System.IO.MemoryStream(bytes));
                Bitmap bitmap = new Bitmap(180, 240, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
                Graphics graphics = Graphics.FromImage(bitmap);
                graphics.Clear(Color.White);
                graphics.DrawRectangle(new Pen(Brushes.Gray, 1), 1, 1, 178, 238);
                graphics.DrawImage(img, 10, 10, 160, 160);
                StringFormat sf = new StringFormat();
                sf.Alignment = StringAlignment.Center;
                sf.LineAlignment = StringAlignment.Center;
                graphics.DrawString(weixinName, new Font("微软雅黑", 18, FontStyle.Bold, GraphicsUnit.Pixel), Brushes.Red, new RectangleF(0, 173, 180, 18), sf);
                graphics.DrawString("微信号:" + weixinNumber, new Font("微软雅黑", 14, FontStyle.Bold, GraphicsUnit.Pixel), Brushes.Red, new RectangleF(0, 194, 182, 17), sf);
                graphics.DrawString(remark, new Font("微软雅黑", 14, FontStyle.Bold, GraphicsUnit.Pixel), Brushes.Red, new RectangleF(0, 215, 180, 17), sf);
                return bitmap;
            }
            catch (Exception ex)
            {
                MyTrace.get().add("GetTcodeBitMap发生错误：" + ex.Message);
                return null;
            }
        }


    }
}
